import React, { useState, useEffect, useRef } from 'react'
import { motion } from 'framer-motion'

const AnimatedNumber = ({ value, duration = 1 }) => {
  const [displayValue, setDisplayValue] = useState(0)
  const prevValue = useRef(0)

  useEffect(() => {
    prevValue.current = displayValue
    const start = performance.now()

    const animate = (timestamp) => {
      const elapsed = timestamp - start
      const progress = Math.min(elapsed / (duration * 1000), 1)
      const current = prevValue.current + (value - prevValue.current) * progress

      setDisplayValue(current)
      if (progress < 1) {
        requestAnimationFrame(animate)
      }
    }

    requestAnimationFrame(animate)
  }, [value, duration])

  const formatNumber = (num) => {
    return num.toLocaleString('en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })
  }

  return (
    <motion.span
      key={displayValue}
      initial={{ y: -10, opacity: 0.5 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ duration: 0.3 }}>
      {formatNumber(displayValue)}
    </motion.span>
  )
}

export default AnimatedNumber
